package business;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.CollectivityTeachingPlanWeek;
import orm.CollectivityWeekArrange;
import orm.IndividualMonthWeekAim;
import orm.IndividualTeachingPlanWeek;
import orm.IndividualWeekArrange;
import orm.IndividualWeekDomain;
import orm.IndividualWeekDomainAim;
import orm.TeachingPlanBaseInfo;
import orm.TopicTransferModel;

import dao.CTeachingPlanWeekDAO;
import dao.CWeekArrangeDAO;
import dao.IMonthWeekAimDAO;
import dao.ITeachingPlanWeekDAO;
import dao.IWeekArrangeDAO;
import dao.IWeekDomainAimDAO;
import dao.IWeekDomainDAO;
import dao.StudentDAO;
import dao.TeacherDAO;
import dao.TeachingPlanBaseInfoDAO;

import util.DBHelper;
import util.Utility;

public class ITeachingPlanWeekInfoServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public ITeachingPlanWeekInfoServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String strFunc = request.getParameter("func");
		Connection con = null;
		Statement stmt = null;
		if (strFunc.equals("load")) {
			gotoITPWInfo(request, response);
			request.getRequestDispatcher("../" + Utility.JSP_ITeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("edit")) {
			String iWeekArrangeID = request.getParameter("IWeekArrangeID");
			IndividualMonthWeekAim[] imwa = null;
			Hashtable<Integer, String> ht = null;
			StudentDAO studentDAO = new StudentDAO();
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			String teacherName = teacher.getTname();
			
			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			IWeekDomainDAO iwdDAO = new IWeekDomainDAO();
			IWeekDomainAimDAO iwdaDAO = new IWeekDomainAimDAO();
			IWeekArrangeDAO iwaDAO = new IWeekArrangeDAO();
			IMonthWeekAimDAO imwaDAO = new IMonthWeekAimDAO();
			TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
			
			try {
				IndividualTeachingPlanWeek itpw = itpwDAO.getitpwonthByCMAID(iWeekArrangeID);
				ArrayList<IndividualWeekDomain> alIWD = iwdDAO.getiwdByCMAID(iWeekArrangeID);
				ArrayList<IndividualWeekDomainAim> alIWDA = iwdaDAO.getiwdaArrByCWAID(iWeekArrangeID);
				ArrayList<IndividualWeekArrange> alIWA = iwaDAO.getiwaByiwaID(iWeekArrangeID);
				ArrayList<IndividualMonthWeekAim> alIMWA = imwaDAO.getimwaByCWAID(iWeekArrangeID);
				ArrayList<TeachingPlanBaseInfo> alMonthThemeName = tpbiDAO.getMonthThemeNameByTPProperty();
				ArrayList<TeachingPlanBaseInfo> alWeekThemeName = tpbiDAO.getWeekThemeNameByTPProperty();
				
				String strTPID = "";
				String tpid = null;
				
				imwa = new IndividualMonthWeekAim[alIMWA.size()];
				for(int k = 0; k < alIMWA.size(); k++){
					String iTPIDS = "";
					strTPID = alIMWA.get(k).getTPID();
					String[] alTPID = strTPID.split(",");
					if(alTPID != null){
						for(int m = 0;m < alTPID.length; m++){
							tpid = alTPID[m];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp != null && !temp.equals("")){
								if(!iTPIDS.equals("")){
									iTPIDS+=",";
								}
								iTPIDS += temp;
							}
						}
					}
					imwa[k] = new IndividualMonthWeekAim();
					imwa[k].setTPIDName(iTPIDS);
				}
				
				ht = studentDAO.getStudentsByIndiTeacherID(teacherID);
				request.setAttribute("Students", ht);
				
				
				request.setAttribute("ITPW", itpw);
				request.setAttribute("IWDArr", alIWD);
				request.setAttribute("IWDAArr", alIWDA);
				request.setAttribute("IWAArr", alIWA);
				request.setAttribute("IMWAArr", alIMWA);
				request.setAttribute("IMWANames", imwa);
				request.setAttribute("MonthThemeNameArr", alMonthThemeName);
				request.setAttribute("WeekThemeNameArr", alWeekThemeName);
				request.setAttribute("IWeekArrangeID", iWeekArrangeID);
					
				request.getRequestDispatcher("../" + 
							Utility.JSP_ITPWeekArrangeEdit).forward(request, response);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else if (strFunc.equals("delete")) {
			String iWeekArrangeID = request.getParameter("IWeekArrangeID");
			try {
				con = DBHelper.getConnection();
				con.setAutoCommit(false);
				stmt = con.createStatement();
				
				ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
				IWeekDomainDAO iwdDAO = new IWeekDomainDAO();
				IWeekDomainAimDAO iwdaDAO = new IWeekDomainAimDAO();
				IWeekArrangeDAO iwaDAO = new IWeekArrangeDAO();
				IMonthWeekAimDAO imwaDAO = new IMonthWeekAimDAO();
				
				itpwDAO.deleteITPWeek(stmt, iWeekArrangeID);
				iwdDAO.deleteIWeekDomain(stmt, iWeekArrangeID);
				iwdaDAO.deleteIWeekDomainAim(stmt, iWeekArrangeID);
				iwaDAO.deleteIWeekArrange(stmt, iWeekArrangeID);
				imwaDAO.deleteIMonthWeekAim(stmt, iWeekArrangeID);
				
				con.commit();
				stmt.close();
				
				gotoITPWInfo(request, response);
				request.getRequestDispatcher("../" + Utility.JSP_ITeachingPlanWeekInfo).forward(request, response);
				
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					con.rollback();
				} catch (SQLException ee) {
					ee.printStackTrace();
				}
			} 
		} else if (strFunc.equals("paging")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("HDPageNo");
			int nPageNo = Integer.parseInt(tmp); 
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
			
			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			IndividualTeachingPlanWeek itpw = null;
			
			try {
				ArrayList al = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
				
				if (strSub == null)
				{
					
				} else if (strSub.equals("start")) {
					nPageNo = 1;
				} else if (strSub.equals("front")) {
					nPageNo--;
				} else if (strSub.equals("next")) {
					nPageNo++;
				} else if (strSub.equals("last")) {
					nPageNo = totalPage ;
				} 
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<IndividualTeachingPlanWeek>();
				ListIterator<IndividualTeachingPlanWeek> it = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate,teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					IndividualTeachingPlanWeek t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					itpw = new IndividualTeachingPlanWeek();
					itpw.setIWeekArrangeID(t.getIWeekArrangeID());
					itpw.setMonthThemeName(t.getMonthThemeName());
					itpw.setWeekThemeName(t.getWeekThemeName());
					itpw.setEnforceTeacherName(t.getEnforceTeacherName());
					itpw.setStarPushDate(t.getStarPushDate());
					itpw.setEndPushDate(t.getEndPushDate());
					
					al.add(itpw);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				request.setAttribute("ITPWList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_ITeachingPlanWeekInfo).forward(request, response);
			
		} else if (strFunc.equals("searchPage")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("PageNo");
			int nPageNo = Integer.parseInt(tmp);
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}

			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			try {
				ArrayList al = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<IndividualTeachingPlanWeek>();
				ListIterator<IndividualTeachingPlanWeek> it = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					IndividualTeachingPlanWeek t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					IndividualTeachingPlanWeek itpw = new IndividualTeachingPlanWeek();
					itpw.setIWeekArrangeID(t.getIWeekArrangeID());
					itpw.setMonthThemeName(t.getMonthThemeName());
					itpw.setWeekThemeName(t.getWeekThemeName());
					itpw.setEnforceTeacherName(t.getEnforceTeacherName());
					itpw.setStarPushDate(t.getStarPushDate());
					itpw.setEndPushDate(t.getEndPushDate());
					
					al.add(itpw);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				
				request.setAttribute("ITPWList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_ITeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("showNetwork")) {
			String strIWeekArrangeID = request.getParameter("IWeekArrangeID");
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			IMonthWeekAimDAO imwaDAO = new IMonthWeekAimDAO();
			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			try {
				List<TopicTransferModel> models = imwaDAO.queryTopicModels(imwaDAO.getTPIDSSByIWeekArrangeID(strIWeekArrangeID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				IndividualTeachingPlanWeek itpw = itpwDAO.getITPWNetByIWAID(strIWeekArrangeID);
				
				request.setAttribute("developmentDomainActivityMapping", developmentDomainActivityMapping);
				request.setAttribute("ITPWArr", itpw);
				request.setAttribute("iWeekArrangeID", strIWeekArrangeID);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_ITPWeekNetwork).forward(request, response);
		} else if (strFunc.equals("SearchCondition")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			IndividualTeachingPlanWeek itpw = null;
			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
		
			try {
				request.setAttribute("pageNo", 1);
				int PageSize = Utility.PageSize;
				ArrayList al = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
		
				al = new ArrayList<IndividualTeachingPlanWeek>();
				ListIterator<IndividualTeachingPlanWeek> it = itpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					IndividualTeachingPlanWeek t = it.next();
					
					itpw = new IndividualTeachingPlanWeek();
					itpw.setIWeekArrangeID(t.getIWeekArrangeID());
					itpw.setMonthThemeName(t.getMonthThemeName());
					itpw.setWeekThemeName(t.getWeekThemeName());
					itpw.setEnforceTeacherName(t.getEnforceTeacherName());
					itpw.setStarPushDate(t.getStarPushDate());
					itpw.setEndPushDate(t.getEndPushDate());
					
					al.add(itpw);
					ii++;
		
					if(ii > (PageSize-1)) {
						break;
					}
				}
				request.setAttribute("ITPWList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_ITeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("ITPWNetworkMore")) {
			String strIWeekArrangeID = request.getParameter("IWeekArrangeID");
			int intActivityOptionSize = Integer.parseInt(request.getParameter("ActivityOptionSize"));
			String strActivityOptionName = request.getParameter("ActivityOptionName");
			strActivityOptionName = new String(strActivityOptionName.getBytes("iso-8859-1"),"utf-8"); 
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			IMonthWeekAimDAO imwaDAO = new IMonthWeekAimDAO();
			ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
			try {
				List<TopicTransferModel> models = imwaDAO.queryTopicModels(imwaDAO.getTPIDSSByIWeekArrangeID(strIWeekArrangeID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				IndividualTeachingPlanWeek itpw = itpwDAO.getITPWNetByIWAID(strIWeekArrangeID);
				
				request.setAttribute("developmentDomainActivityMapping", developmentDomainActivityMapping);
				request.setAttribute("ITPWArr", itpw);
				request.setAttribute("iWeekArrangeID", strIWeekArrangeID);
				request.setAttribute("ActivityOptionSize", intActivityOptionSize);
				request.setAttribute("ActivityOptionName", strActivityOptionName);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_ITPWNetworkMore).forward(request, response);
			
		}
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void gotoITPWInfo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException{
		IndividualTeachingPlanWeek itpw = null;
		ITeachingPlanWeekDAO itpwDAO = new ITeachingPlanWeekDAO();
		TeacherDAO teacherDAO = new TeacherDAO();
		
		com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
		
		Integer teacherID = teacher.getTeacherId();
	
		try {
			request.setAttribute("pageNo", 1);
			int PageSize = Utility.PageSize;
			ArrayList al = itpwDAO.getAllITeachingPlanWeek(teacherID);
			int totalPage = 0;
			if (al.size() % PageSize == 0) {
				totalPage = al.size()/PageSize;
				request.setAttribute("totalPage",totalPage);
			} else {
				totalPage = (al.size()/PageSize) + 1;
				request.setAttribute("totalPage",totalPage);
			}
	
			al = new ArrayList<IndividualTeachingPlanWeek>();
			ListIterator<IndividualTeachingPlanWeek> it = itpwDAO.getAllITeachingPlanWeek(teacherID).listIterator();
			int ii = 0;
			while (it.hasNext()) {
				IndividualTeachingPlanWeek t = it.next();
				
				itpw = new IndividualTeachingPlanWeek();
				itpw.setIWeekArrangeID(t.getIWeekArrangeID());
				itpw.setMonthThemeName(t.getMonthThemeName());
				itpw.setWeekThemeName(t.getWeekThemeName());
				itpw.setEnforceTeacherName(t.getEnforceTeacherName());
				itpw.setStarPushDate(t.getStarPushDate());
				itpw.setEndPushDate(t.getEndPushDate());
				
				al.add(itpw);
				ii++;
	
				if(ii > (PageSize-1)) {
					break;
				}
			}
			request.setAttribute("ITPWList", al);	
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	}

}
